package com.example.library_common.loader;

import android.content.Context;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatDialog;

import com.example.library_common.R;
import com.example.library_common.global.AppGlobals;
import com.example.library_common.utils.QMUIDeviceHelper;
import com.example.library_common.utils.QMUIDisplayHelper;
import com.example.library_common.view.LoadingIndicatorView;

import java.util.ArrayList;

public final class LatteLoader {

    private static final int LOADER_SIZE_SCALE = 8;
    private static final int LOADER_OFFSET_SCALE = 10;

    private static final ArrayList<AppCompatDialog> LOADERS = new ArrayList<>();

//    private static final Indicator DEFAULT_LOADER = new BallClipRotateMultipleIndicator();

    private static AppCompatDialog createDialog(
            Context context, LoadingIndicatorView avLoadingIndicatorView) {

        final AppCompatDialog dialog = new AppCompatDialog(context, R.style.loader_dialog);
        int deviceWidth = QMUIDisplayHelper.getScreenWidth(AppGlobals.getApplication());
        int deviceHeight = QMUIDisplayHelper.getScreenHeight(AppGlobals.getApplication());
        final Window dialogWindow = dialog.getWindow();
        dialog.setContentView(avLoadingIndicatorView);

        if (dialogWindow != null) {
            final WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = deviceWidth / LOADER_SIZE_SCALE;
            lp.height = deviceHeight / LOADER_SIZE_SCALE;
            lp.height = lp.height + deviceHeight / LOADER_OFFSET_SCALE;
            lp.gravity = Gravity.CENTER;
        }
        LOADERS.add(dialog);
        return dialog;
    }

//    public static void showLoading(Context context, Enum<LoaderStyle> type) {
//        showLoading(context, type.name());
//    }

    public static void showLoading(Context context) {
        final LoadingIndicatorView avLoadingIndicatorView = new LoadingIndicatorView(context);
//        avLoadingIndicatorView.setIndicator(type);
        createDialog(context, avLoadingIndicatorView).show();
    }

//    public static void showLoading(Context context, Indicator indicator) {
//        final LoadingIndicatorView avLoadingIndicatorView = new LoadingIndicatorView(context);
//        avLoadingIndicatorView.setIndicator(indicator);
//        createDialog(context, avLoadingIndicatorView).show();
//    }


//    public static void showLoading(Context context) {
//        showLoading(context, DEFAULT_LOADER);
//    }

    public static void stopLoading() {
        for (AppCompatDialog dialog : LOADERS) {
            if (dialog != null) {
                if (dialog.isShowing()) {
                    dialog.cancel();
                }
            }
        }
        LOADERS.clear();
    }
}